const finance = require('../../../utils/finance')
const financeCategory = require('../../../utils/finance-category')
const financeExport = require('../../../utils/finance-export')
const app = getApp()
Page({
  data: {
    // 搜索表单数据
    searchForm: {
      keyword: '',
      minAmount: '',
      maxAmount: '',
      startDate: '',
      endDate: ''
    },
    // 账户相关
    accountList: [],
    accountIndex: 0,
    // 记账类型相关
    typeList: [
      { name: '全部类型', value: '' },
      { name: '收入', value: 'income' },
      { name: '支出', value: 'expense' }
    ],
    typeIndex: 0,
    // 分类相关
    categoryList: [],
    categoryIndex: -1,
    incomeCategoryList: [],
    expenseCategoryList: [],
    showCategoryModal: false,
    // 搜索结果
    searchResults: [],
    // 分页相关
    hasMore: true,
    pageNum: 1,
    pageSize: 8,
    // 排序类型
    sortField: 'time', // 'time' 或 'amount'
    sortOrder: 'desc', // 新增，默认倒序
    // 页面状态
    loading: false,
    hasSearched: false,
    // 页面初始化状态
    isInitialized: false,
    showAccountSelector: false,
    // 分类选择器索引
    categorySelectorIndex: -1,
  },

  async onLoad(options) {
    // 1. 解析参数
    const { category, type, yearMonth, date, accountId } = options;
    if (accountId && type) {
      // 进来页面有参数的情况， 也需要初始化账户和分类数据
      await this.initPageData();
      // 处理分页中文乱码
      const decodedCategory = category ? decodeURIComponent(category) : '';
      // 2. 处理 yearMonth → dateStart/dateEnd
      let dateStart = '', dateEnd = '';
      if (yearMonth) {
        const [year, month] = yearMonth.split('-');
        dateStart = `${year}-${month}-01`;
        // 计算该月最后一天
        const lastDay = new Date(year, month, 0).getDate();
        dateEnd = `${year}-${month}-${lastDay}`;
      }
      let categoryIndex = -1;
      let categoryList = [];
      if (type === 'income') {
        categoryList = this.data.incomeCategoryList;
        categoryIndex = categoryList.findIndex(item => item.name === decodedCategory);
      } else if (type === 'expense') {
        categoryList = this.data.expenseCategoryList;
        categoryIndex = categoryList.findIndex(item => item.name === decodedCategory);
      }
      const typeIndex = this.data.typeList.findIndex(item => item.value === type);
      const accountIndex = this.data.accountList.findIndex(item => item.id === accountId);
      // 4. 设置到 data
      this.setData({
        categoryList: categoryList,
        accountIndex: accountIndex,
        categoryIndex: categoryIndex,
        typeIndex: typeIndex,
        'searchForm.startDate': dateStart,
        'searchForm.endDate': dateEnd
      }, () => {
        // 5. 自动触发搜索
        this.onSearch();
      });
    } else{
      // 进来页面没有参数的情况
      this.initPageData();
    }
  },

  onShow() {
    // 只有在页面已经初始化后才执行刷新，避免重复初始化
    if (this.data.isInitialized) {
      this.setData({ pageNum: 1, hasMore: true });
      this.onSearch();
    }
  },

  async initByOptions(options) {
    this.setData({
      searchForm: {
        keyword: options.keyword,
        minAmount: options.minAmount,
        maxAmount: options.maxAmount,
      }
    });
  },

  async initPageData() {
    await this.initAccountList();
    await this.initCategoryList();
    this.setData({ isInitialized: true });
  },
  // 处理账户数据
  async initAccountList() {
    const { accountList, accountIndex } = await app.getAccountGlobal();
    this.setData({ accountList, accountIndex });
  },
  async initCategoryList() {
    try {
      const res = await financeCategory.getCategoryList();
      if (res && Array.isArray(res)) {
        // 将分类按类型分组
        const incomeCategoryList = res.filter(item => item.type === 'income' || item.financeType === 'income');
        const expenseCategoryList = res.filter(item => item.type === 'expense' || item.financeType === 'expense');
        
        this.setData({
          categoryList: res,
          incomeCategoryList: incomeCategoryList,
          expenseCategoryList: expenseCategoryList
        });
      }
    } catch (e) {
      console.error('获取分类列表失败:', e);
    }
  },

  // 表单输入事件
  onKeywordInput(e) {
    this.setData({
      'searchForm.keyword': e.detail.value
    });
  },

  onMinAmountInput(e) {
    this.setData({
      'searchForm.minAmount': e.detail.value
    });
  },

  onMaxAmountInput(e) {
    this.setData({
      'searchForm.maxAmount': e.detail.value
    });
  },

  onStartDateChange(e) {
    this.setData({
      'searchForm.startDate': e.detail.value
    });
  },

  onEndDateChange(e) {
    this.setData({
      'searchForm.endDate': e.detail.value
    });
  },

  /**
   * 切换账号
   * @param {*} e 
   */
  onAccountChange(e) {
    const idx = e.detail.value;
    this.setData({ pageNum: 1, hasMore: true, accountIndex: idx });
    this.onSearch();
  },

  onTypeChange(e) {
    const idx = e.detail.value;
    let categorySelectorIndex = -1;
    
    // 如果之前有选中的分类，需要重新计算在对应类型列表中的索引
    if (this.data.categoryIndex >= 0 && this.data.categoryList[this.data.categoryIndex]) {
      const selectedCategory = this.data.categoryList[this.data.categoryIndex];
      if (idx === 1) { // 收入类型
        categorySelectorIndex = this.data.incomeCategoryList.findIndex(item => item.id === selectedCategory.id);
      } else if (idx === 2) { // 支出类型
        categorySelectorIndex = this.data.expenseCategoryList.findIndex(item => item.id === selectedCategory.id);
      } else { // 全部类型
        // categorySelectorIndex = this.data.categoryIndex;
      }
    }
    
    this.setData({
      typeIndex: idx,
      categoryIndex: -1, // 重置分类选择
      categorySelectorIndex: categorySelectorIndex
    });
  },

  // 显示分类选择弹出框
  showCategoryModal() {
    this.setData({
      showCategoryModal: true
    });
  },

  // 隐藏分类选择弹出框
  hideCategoryModal() {
    this.setData({
      showCategoryModal: false
    });
  },

  // 选择分类
  onCategorySelect(e) {
    const { index, type, item } = e.detail;
    
    // 根据当前选择的类型，在对应的分类列表中查找
    let categoryList = [];
    let originalIndex = -1;
    let componentIndex = -1;
    
    if (type === 'income') {
      // 收入类型：在完整分类列表中查找对应的收入分类
      categoryList = this.data.categoryList;
      originalIndex = categoryList.findIndex(cat => cat.id === item.id);
      // 在收入分类列表中的索引，用于组件显示
      componentIndex = this.data.incomeCategoryList.findIndex(cat => cat.id === item.id);
    } else if (type === 'expense') {
      // 支出类型：在完整分类列表中查找对应的支出分类
      categoryList = this.data.categoryList;
      originalIndex = categoryList.findIndex(cat => cat.id === item.id);
      // 在支出分类列表中的索引，用于组件显示
      componentIndex = this.data.expenseCategoryList.findIndex(cat => cat.id === item.id);
    } else {
      // 全部类型时，使用完整的分类列表
      categoryList = this.data.categoryList;
      originalIndex = index; // 在完整列表中的索引
      componentIndex = index; // 组件中的索引
    }
    
    this.setData({
      categoryIndex: originalIndex,
      categoryList: categoryList, // 更新当前使用的分类列表
      categorySelectorIndex: componentIndex,
      showCategoryModal: false
    });
  },
  // 搜索和重置
  async loadPage(pageNum = 1, append = false) {
    if (this.data.loading) return;
    this.setData({ loading: true });
    try {
      const searchParams = this.buildSearchParams();
      searchParams.current = pageNum;
      searchParams.size = this.data.pageSize;
      const res = await finance.searchRecordPageList(searchParams);
      const records = res && Array.isArray(res.records) ? res.records : [];
      const total = res && typeof res.total === 'number' ? res.total : 0;
      const pageResults = records.map(item => ({
        id: item.id,
        type: item.financeType,
        category: item.categoryName,
        financeDesc: item.financeDesc || '',
        amount: item.totalAmount,
        financeDate: item.financeDate,
        financeTime: item.financeTime
      }));
      const newResults = append ? [...this.data.searchResults, ...pageResults] : pageResults;
      // 去重：只保留 id 唯一的项
      const uniqueResults = [];
      const idSet = new Set();
      for (const item of newResults) {
        if (!idSet.has(item.id)) {
          uniqueResults.push(item);
          idSet.add(item.id);
        }
      }
      const hasMore = uniqueResults.length < total;
      this.setData({
        searchResults: uniqueResults,
        loading: false,
        hasSearched: true,
        hasMore,
        pageNum // 只记录当前页，不自增
      });
    } catch (e) {
      this.setData({ loading: false });
      wx.showToast({ title: (e && e.data && e.data.msg) || '加载失败', icon: 'none' });
    }
  },

  async onSearch() {
    if (!this.validateSearchForm()) return;
    this.setData({ pageNum: 1, hasMore: true });
    await this.loadPage(1, false);
  },

  async onLoadMore() {
    if (!this.data.hasMore || this.data.loading) return;
    await this.loadPage(this.data.pageNum + 1, true);
  },

  async onExport() {
    if (!this.validateSearchForm()) return;
    wx.showLoading({ title: '导出中...' });
    try {
      const params = this.buildSearchParams();
      await financeExport.exportRecords(params);
      wx.hideLoading();
      wx.showModal({
        title: '导出成功',
        content: '导出结果请异步到设置->数据导出页面查看',
        confirmText: '查看',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({ url: '/pages/finance/export/export' });
          }
        }
      });
    } catch (e) {
      wx.hideLoading();
      wx.showToast({ title: (e && e.data && e.data.msg) || '导出失败', icon: 'none' });
    }
  },

  validateSearchForm() {
    if (!this.data.accountList.length) {
      wx.showToast({ title: '请先选择账户', icon: 'none' });
      return false;
    }
    
    if (this.data.accountIndex < 0) {
      wx.showToast({ title: '请选择账户', icon: 'none' });
      return false;
    }

    const { minAmount, maxAmount, startDate, endDate } = this.data.searchForm;
    if (minAmount && maxAmount && parseFloat(minAmount) > parseFloat(maxAmount)) {
      wx.showToast({ title: '最小金额不能大于最大金额', icon: 'none' });
      return false;
    }

    // 新增：校验日期区间
    if (startDate && endDate) {
      if (endDate < startDate) {
        wx.showToast({ title: '结束日期不能早于开始日期', icon: 'none' });
        return false;
      }
    }

    return true;
  },

  buildSearchParams() {
    const { searchForm } = this.data;
    const account = this.data.accountList[this.data.accountIndex];
    const category = this.data.categoryIndex >= 0 ? this.data.categoryList[this.data.categoryIndex] : null;
    const selectedType = this.data.typeList[this.data.typeIndex];
    return {
      accountBookId: account.id,
      keyword: searchForm.keyword,
      categoryCode: category ? category.name : '',
      financeType: selectedType.value, // 添加记账类型参数
      minAmount: searchForm.minAmount,
      maxAmount: searchForm.maxAmount,
      startDate: searchForm.startDate,
      endDate: searchForm.endDate,
      sortField: this.data.sortField, // 排序字段 desc或者asc
      sortOrder: this.data.sortOrder // 新增，asc/desc
    };
  },
  onReset() {
    this.setData({
      searchForm: {
        keyword: '',
        minAmount: '',
        maxAmount: '',
        startDate: this.data.searchForm.startDate,
        endDate: this.data.searchForm.endDate
      },
      typeIndex: 0,
      categoryIndex: -1,
      categorySelectorIndex: -1,
      searchResults: [],
      hasSearched: false,
      hasMore: true,
      pageNum: 1
    });
  },

  onSortChange(e) {
    const sortField = e.currentTarget.dataset.field;
    // 判断是否点击了当前tab
    if (sortField === this.data.sortField) {
      // 切换排序顺序
      const newOrder = this.data.sortOrder === 'desc' ? 'asc' : 'desc';
      this.setData({ sortOrder: newOrder, pageNum: 1, hasMore: true });
    } else {
      // 切换tab，默认倒序
      this.setData({ sortField, sortOrder: 'desc', pageNum: 1, hasMore: true });
    }
    this.onSearch();
  },

  onClearType() {
    this.setData({ typeIndex: 0, categoryIndex: -1 });
  },
  onClearCategory() {
    this.setData({ 
      categoryIndex: -1,
      categorySelectorIndex: -1
    });
  },
  onClearMinAmount() {
    this.setData({ 'searchForm.minAmount': '' });
  },
  onClearMaxAmount() {
    this.setData({ 'searchForm.maxAmount': '' });
  },
  onClearStartDate() {
    this.setData({ 'searchForm.startDate': '' });
  },
  onClearEndDate() {
    this.setData({ 'searchForm.endDate': '' });
  },
  clickShowAccountSelector() {
    this.setData({ showAccountSelector: true });
  },

  async onSelectAccount(e) {
    const idx = e.detail.index;
    // 复用原有onAccountChange逻辑
    await this.onAccountChange({ detail: { value: idx } });
  },
}); 